package com.je.core.thread;

import com.je.core.util.JEUUID;
import com.je.core.util.SecurityUserHolder;
import com.je.core.util.StringUtil;
import com.je.core.util.bean.BeanUtils;
import com.je.core.util.bean.DynaBean;
import com.je.paas.document.model.MetadataEnum;
import com.je.paas.document.model.UploadTypeEnum;
import com.je.paas.document.service.DocumentBusService;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * @Auther: yuchunhui 文件保存业务元数据信息
 * @Date: 11 37
 * @Description:
 */
public class FileMetadataTread extends Thread {
    private DocumentBusService documentBusService;

    private DynaBean dynaBean;
    private String batchFilesFields;
    private String uploadableFields;
    private String funcCode;
    private String type;

    /**
     * todo 弃用
     * @param dynaBean
     * @param batchFilesFields
     * @param uploadableFields
     * @param funcCode
     * @param type
     * @Description documentBusService无法注入进来，因此弃用
     */
    public FileMetadataTread(DynaBean dynaBean, String batchFilesFields, String uploadableFields, String funcCode, String type) {
        this.dynaBean = dynaBean;
        this.batchFilesFields = batchFilesFields;
        this.uploadableFields = uploadableFields;
        this.funcCode = funcCode;
        this.type = type;
    }

    public FileMetadataTread(DynaBean dynaBean, String batchFilesFields, String uploadableFields, String funcCode, String type, DocumentBusService documentBusService) {
        this.dynaBean = dynaBean;
        this.batchFilesFields = batchFilesFields;
        this.uploadableFields = uploadableFields;
        this.funcCode = funcCode;
        this.type = type;
        this.documentBusService = documentBusService;
    }

    @Override
    public void run() {
        if (type.equals("save")) {
            doSaveFileMetadata();
        }
    }


    private void doSaveFileMetadata() {
        //获取表名
        String tableCode = dynaBean.getStr(BeanUtils.KEY_TABLE_CODE);
        //获取主键字段名
        String pkCode = dynaBean.getStr(BeanUtils.KEY_PK_CODE);
        //设置主键，因为传过来的DynaBean可能是未设置主键的
        String pkValue = dynaBean.getPkValue();
        if (StringUtil.isEmpty(pkValue)) {
            pkValue = JEUUID.uuid();
            dynaBean.set(pkCode, pkValue);
        }

        //组装元数据信息
        com.alibaba.fastjson.JSONObject metadataObject = new com.alibaba.fastjson.JSONObject();
        metadataObject.put(MetadataEnum.tableCode.getCode(), tableCode);
        metadataObject.put(MetadataEnum.pkValue.getCode(), pkValue);
        metadataObject.put(MetadataEnum.funcCode.getCode(), funcCode);
        metadataObject.put(MetadataEnum.uploadType.getCode(), UploadTypeEnum.FORM.getCode());
        metadataObject.put(MetadataEnum.tenantId.getCode(), SecurityUserHolder.getCurrentUser().getZhId());

        String userId = SecurityUserHolder.getCurrentUser().getUserId();

        //遍历多附件字段信息
        if (StringUtil.isNotEmpty(batchFilesFields)) {
            for (String filedCode : batchFilesFields.split(",")) {

                //设置元数据字段名
                metadataObject.put(MetadataEnum.fieldCode.getCode(), filedCode);

                //获取字段中附件集合
                JSONArray files = JSONArray.fromObject(StringUtil.getDefaultValue(dynaBean.getStr(filedCode), "[]"));
                //记录有效key
                List<String> usedFileKey = new ArrayList<>();
                //遍历附件
                for (Integer i = 0; i < files.size(); i++) {
                    JSONObject fileObj = files.getJSONObject(i);
                    //获取文件key
                    String fileKey = fileObj.optString("path");
                    usedFileKey.add(fileKey);
                }

                //保存文件元数据
                documentBusService.saveFileMetadata(userId, metadataObject, usedFileKey);

                //清理字段相关附件信息
                documentBusService.updateFiledFile(userId, tableCode, pkValue, filedCode, usedFileKey);
            }
        }
        //遍历单附件字段信息
        if (StringUtil.isNotEmpty(uploadableFields)) {

            for (String fieldCode : uploadableFields.split(",")) {

                //设置元数据字段名
                metadataObject.put(MetadataEnum.fieldCode.getCode(), fieldCode);
                //记录有效key
                List<String> usedFileKey = new ArrayList<>();
                //获取文件key
                String value = StringUtil.getDefaultValue(dynaBean.getStr(fieldCode));
                if (StringUtil.isNotEmpty(value) && value.contains("*")) {
                    String[] fileMsg = value.split("\\*");
                    usedFileKey.add(fileMsg[fileMsg.length - 1]);
                }
                //保存文件元数据
                documentBusService.saveFileMetadata(userId, metadataObject, usedFileKey);
                //清理字段相关附件信息
                documentBusService.updateFiledFile(userId, tableCode, pkValue, fieldCode, usedFileKey);
            }
        }
    }
}
